﻿using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Settings;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WxSDK.Config;

namespace WxSDK.WxPay
{
	/// <summary>
	/// 微信支付APIv3版本
	/// </summary>
	public class WxPayApiV3
    {
        /// <summary>
        /// 微信支付请求客户端实例
        /// </summary>
        public static readonly WechatTenpayClient Instance;

        static WxPayApiV3()
        {
            var certificateManager = new InMemoryCertificateManager();
            Instance = new WechatTenpayClient(new WechatTenpayClientOptions()
            {
                MerchantId = WxConfig.MCHID,
                MerchantV3Secret = WxConfig.KEYv3,
                MerchantCertificateSerialNumber = WxConfig.WxSSLCERT_SerialNo,
                MerchantCertificatePrivateKey = WxConfig.WxSSLCERT_PRIVATE_KEY,
                AutoEncryptRequestSensitiveProperty = true,
                AutoDecryptResponseSensitiveProperty = true,
                PlatformCertificateManager = certificateManager
            });
        }

        /// <summary>
        /// 初始化微信支付平台证书管理器，从微信支付平台下载最新的证书，并填充进管理器中。
        /// </summary>
        /// <returns></returns>
        internal static async Task InitializeCertificateManagerAsync()
        {
            var request = new QueryCertificatesRequest();
            var response = await Instance.ExecuteQueryCertificatesAsync(request);

            response = Instance.DecryptResponseSensitiveProperty(response);
            foreach (var certificateModel in response.CertificateList)
            {
                Instance.PlatformCertificateManager.AddEntry(new CertificateEntry(certificateModel));
            }
        }
    }
}
